import { inject, type DefineComponent, type Plugin } from "vue";
import DaisyDialog from "./DaisyDialog.vue";

declare global {
  interface DaisyDialogPlugin {
    showDialog: (instance: DefineComponent) => void;
    hideDialog: (instance: DefineComponent) => void;
    toggleDialog: (instance: DefineComponent) => void;
  }
  interface DaisyPlugin {
    dialog: DaisyDialogPlugin;
  }
}
declare module "vue" {
  interface ComponentCustomProperties {
    $daisy: DaisyPlugin;
  }
}

function getInstance(instance: DefineComponent) {
  if (!instance) {
    console.error("找不到dialog", instance);
    return null;
  }
  return instance;
}

const plugin: DaisyDialogPlugin = {
  showDialog(instance) {
    const element = getInstance(instance);
    element?.show();
  },
  hideDialog(instance) {
    const element = getInstance(instance);
    element?.hide();
  },
  toggleDialog(instance) {
    const element = getInstance(instance);
    element?.toggle();
  },
};

export const DaisyDialogPlugin: Plugin = {
  install(app) {
    app.component("DaisyDialog", DaisyDialog);
    if (app.config.globalProperties.$daisy) {
      app.config.globalProperties.$daisy.dialog = plugin;
    } else {
      const p: any = {
        dialog: plugin,
      };
      app.config.globalProperties.$daisy = p;
    }

    const daisy = inject<DaisyPlugin>("daisy");
    if (daisy) {
      daisy.dialog = plugin;
      app.provide("daisy", daisy);
    } else {
      app.provide("daisy", {
        dialog: plugin,
      });
    }
  },
};
export default DaisyDialogPlugin;
